package com.yst.gateway.monitor.common.batch;

import java.lang.reflect.Method;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;

public class BatchSqlDaoImpl<T1, T2> implements BatchSqlDao<T1, T2>{

	@Resource
	private SqlSessionTemplate sqlSessionTemplate;

	@Override
	public void batchInsert(List<T1> list, int batchSize,Class<T2> clazz) {		
		if(list!=null&&list.size()>0){
			SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		    try {
				T2 t2= (T2) session.getMapper(clazz);
		    	Method m1 = clazz.getDeclaredMethod("insert",list.get(0).getClass());
		    	for (int i = 0; i < list.size(); i++) {
		    		m1.invoke(t2,list.get(i)); 
	                if (i % batchSize == 0 || i == list.size() - 1) {
	                	//手动每1000个一提交，提交后无法回滚
	                	session.commit();
	                	//清理缓存，防止溢出
	                	session.clearCache();
	                }
		        }
		    } catch (Exception e) {e.printStackTrace();
		    	session.rollback();
		    } finally {
		        session.close();
		    }
		}
	}
}
